import Vue from "vue";
import Vuex from 'vuex';
import {
  INCREMENT,
}from "./Mutations-types"

//1.安装插件
Vue.use(Vuex)

//2.创建对象
const moduleA ={
  state:{
    name:'zhangsan'
  },
  mutations:{
    updatename(state,payload){
      state.name = payload
    }
  },
  getters:{
    fullname(state){
      return state.name + '拼接'
    },
    fullname2(state, getter){
      return getter.fullname + '第二次拼接'
    },
    fullname3(state,getter,rootState){
      return getter.fullname2 + rootState.counter
    }
  },
  actions:{
    aupdatename(context){
      setTimeout(()=>{
        context.commit('updatename','wangwu')
      },1000)
    }
  },
}


const store = new Vuex.Store({
  state:{
    //用于保存状态
    counter:1000,
    students:[
        { id:100, name:'why', age:30},
        { id:101, name:'coder', age:31},
        { id:102, name:'flower', age:16},
        { id:103, name:'sky', age:15},
      ],
    info:{
      name:'kobe',
      age:40,
      height:1.98
    }
  },
  mutations:{
    //方法   有一个默认参数state
    [INCREMENT](state){
      state.counter++
    },
    decrement(state){
      state.counter--
    },
    //普通的接收
    // incrementcount(state,count){
    //   state.counter += count
    // },

    //特殊的接收
    incrementcount(state,payload){
      state.counter += payload.counter
    },
    addStudent(state,stu){
      state.students.push(stu)
    },
    updateinfo(state){
      state.info.name='coderwhy'
      //不能在这里进行异步操作
      // setTimeout(()=>{
      //   state.info.name = 'coderwhy'
      // },1000)
    }
  },
  actions:{
    //context：上下文
    //做法一：
    // actionupdateinfo(context,payload){
    //   setTimeout(()=>{
    //     context.commit('updateinfo')
    //     console.log(payload.message);
    //     payload.success()
    //   },1000)
    // },
    //做法二：
    actionupdateinfo(context,payload){
      return new Promise((resolve, reject) => {
        setTimeout(()=>{
          context.commit('updateinfo')
          console.log(payload);

          resolve('内部信息处理完成')
        },1000)
      })
    },
  },
  getters:{
    //类似组件中的计算属性
    powerCounter(state){
      return state.counter * state.counter
    },
    more20stu(state){
      return state.students.filter(s=> s.age>20)
    },
    more20stuLength(state, getters){
      return getters.more20stu.length
    },
    moreAgeStu(state){
      return function (age) {
        return state.students.filter(s=> s.age >age)
      }
    },
  },
  modules:{
    a:moduleA,
  },
})

//3.导出Store
export default  store

//对象的解构
// const obj ={
//   name:'why',
//   age:18,
//   height: 1.88,
// }
// const {name,age,height} = obj;
// console.log(name);
